package ma.belsoft.syga.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import ma.belsoft.syga.model.Ville;
import ma.belsoft.syga.service.VilleManager;
import ma.belsoft.syga.webapp.action.BaseAction;

import java.util.List;

public class VilleAction extends BaseAction implements Preparable {
    private VilleManager villeManager;
    public VilleManager getVilleManager() {
		return villeManager;
	}

	public void setVilleManager(VilleManager villeManager) {
		this.villeManager = villeManager;
	}

	private List villes;
    private Ville ville;
    private Long id;
    private String query;

   

    public List getVilles() {
        return villes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String villeId = getRequest().getParameter("ville.id");
            if (villeId != null && !villeId.equals("")) {
                ville = villeManager.get(new Long(villeId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        villes = villeManager.search(query, Ville.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Ville getVille() {
        return ville;
    }

    public void setVille(Ville ville) {
        this.ville = ville;
    }

    public String delete() {
        villeManager.remove(ville.getId());
        saveMessage(getText("ville.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            ville = villeManager.get(id);
        } else {
            ville = new Ville();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (ville.getId() == null);

        villeManager.save(ville);

        String key = (isNew) ? "ville.added" : "ville.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}